package com.labichaoka.chaoka.ui.home.fragment.ku;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.labichaoka.chaoka.R;
import com.labichaoka.chaoka.base.BaseFragment;
import com.labichaoka.chaoka.utils.SharedPreferencesManager;
import com.labichaoka.chaoka.utils.ToastUtils;

import butterknife.BindView;

public class KuFragment extends BaseFragment {
    @BindView(R.id.wv_content)
    WebView wvContent;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    @BindView(R.id.tv_title)
    TextView txtTitle;
    @BindView(R.id.close)
    TextView close;
    @BindView(R.id.back_layout)
    RelativeLayout goBack;
    @BindView(R.id.right_container)
    RelativeLayout rightLayout;


    private String url;

    @Override
    protected int initLayoutId() {
        return R.layout.fragment_ku;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {
        url ="https://cscard.labifenqi.com/money-library?app=1" ;
        WebSettings settings = wvContent.getSettings();
        //启用支持javascript
        settings.setJavaScriptEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setAllowContentAccess(true); // 是否可访问Content Provider的资源，默认值 true
        settings.setAllowFileAccess(true);    // 是否可访问本地文件，默认值 true
        settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // 开启 DOM storage API 功能
        settings.setDomStorageEnabled(true);
        //开启 database storage API 功能
        settings.setDatabaseEnabled(true);

        //自适应屏幕
        //settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        //辅助WebView设置处理关于页面跳转，页面请求等操作
        wvContent.setWebViewClient(new MyWebViewClient());
        //辅助WebView处理图片上传操作
        wvContent.setWebChromeClient(new MyChromeWebClient());
        //加载地址
        wvContent.loadUrl(url);

        wvContent.addJavascriptInterface(new Object(){
            @JavascriptInterface
            public void openNativeActivity(String className) {

            }

        },"SuperCard");

        wvContent.setOnKeyListener((v, keyCode, event) -> {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    //这里处理返回键事件
                    if (wvContent.canGoBack()) {
                        wvContent.goBack();
                        SharedPreferencesManager.getInstance().putString("flag","0");
                    }else{
                        SharedPreferencesManager.getInstance().putString("flag","1");
//                        goBack.setVisibility(View.GONE);
                    }
                }
            }
            return false;
        });

    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }


        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            ToastUtils.show("加载失败，请稍后重试");
        }

        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse
                errorResponse) {
            super.onReceivedHttpError(view, request, errorResponse);

        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }

        @Override
        public boolean shouldOverrideUrlLoading(android.webkit.WebView view, String url) {
            if (url.trim().startsWith("tel")) {//特殊情况tel，调用系统的拨号软件拨号【<a href="tel:1111111111">1111111111</a>】
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(url));
                startActivity(i);
            } else {
                //Android8.0以下的需要返回true 并且需要loadUrl；8.0之后效果相反
                if (Build.VERSION.SDK_INT < 26) {
                    view.loadUrl(url);
                    return true;
                }
                //view.loadUrl(url);
            }
//            return super.shouldOverrideUrlLoading(view, url);
            return false;
        }
    }

    @Override
    public void onResume() {
        super.onResume();


    }

    private class MyChromeWebClient extends WebChromeClient {
        @Override
        public void onProgressChanged(android.webkit.WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            if (newProgress >= 100) {
                progressBar.setVisibility(View.GONE);
            } else {
                if (progressBar.getVisibility() == View.GONE) {
                    progressBar.setVisibility(View.GONE);
                } else {
                    progressBar.setVisibility(View.VISIBLE);
                }
                progressBar.setProgress(newProgress);
            }

        }


        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);

            if (title != null && !view.getUrl().contains(title)) {
                if (title.length() > 8) {
                    title = title.substring(0, 8) + "...";
                }
                txtTitle.setText(title);
            }

            if (view.canGoBack()) {
                goBack.setVisibility(View.VISIBLE);
            } else {
                goBack.setVisibility(View.GONE);
            }
        }

    }



}
